<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>上传下载</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <el-row :gutter="24"><!-- gutter是指定每个分栏的间隔 -->
<!--                 分栏一共占24格，给搜索框7格，添加按钮4格-->
                <el-col :span="7">
                    <!-- 搜索与添加区域 -->
                    <div style="display: flex; align-items: center;">
                      <el-input placeholder="请输入内容" clearable @clear="getUsers()" v-model="queryInfo.query" @keyup.enter="handleEnterKey"></el-input>
                      <el-button type="primary" size="mini" @click="getUsers()">搜索</el-button>
                    </div>
                </el-col>
                <el-col :span="1">
                    <el-button type="primary" @click="addDialogVisible = true">添加</el-button>
                </el-col>
                <el-col :span="2">
                    <el-button type="primary" id="yulan" @click="openDialog">预览/下载</el-button>
                </el-col>

            </el-row>
            <el-table v-loading="loading" :data="users" border stripe ><!-- 带边框、斑马纹 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column label="类型" prop="type"></el-table-column>
                <el-table-column label="问题" prop="problem">
                    <template #default="scope">
                      <div class="single-line">
                        {{ scope.row.problem }}
                      </div>
                    </template>
                </el-table-column>
                <el-table-column label="相似问题" prop="Similarity_problem">
                    <template #default="scope">
                      <div class="single-line">
                        {{ scope.row.Similarity_problem }}
                      </div>
                    </template>
                </el-table-column>
                <el-table-column label="答案" prop="answer">
                    <template #default="scope">
                      <div class="single-line">
                        {{ scope.row.answer }}
                      </div>
                    </template>
                </el-table-column>
                <el-table-column label="修改人" prop="user"></el-table-column>
                <el-table-column label="修改时间" prop="time"></el-table-column>
                <el-table-column label="操作" width="130px">
                    <template #default="scope">
                        <!-- 放置修改、删除和分配角色按钮 -->
                        <el-tooltip effect="dark" content="修改" placement="top">
                        <el-button type="primary"  size="mini" @click="showEditDialog(scope.row.id)"><el-icon><Edit /></el-icon></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="删除" placement="top">
                        <el-button type="danger"  size="mini" @click="removeUserById(scope.row.id)"><el-icon><Delete /></el-icon></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
          <!-- 分页区域 -->
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
          <!-- 添加用户的对话框 -->
            <el-dialog title="添加" v-model="addDialogVisible" width="40%" @close="addDialogClosed">
            <!-- 内容主体区 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="90px" @submit.prevent="onSubmit">
               <el-form-item label="类型" prop="type"> <!-- prop是验证规则属性 -->
                  <el-autocomplete
                    v-model="addForm.type"
                    :fetch-suggestions="querySearchAsync"
                    placeholder="请输入内容"
                    @select="handleSelect"
                  ></el-autocomplete>
              </el-form-item>
              <el-form-item label="问题" prop="problem"> <!-- prop是验证规则属性 -->
                  <el-input
                    v-model="addForm.problem"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    type="textarea"
                    placeholder="请输入你的问题，例如：云主机怎么申请"
                  />
              </el-form-item>
              <el-form-item label="相似问题" prop="Similarity_problem">
                  <el-input
                    v-model="addForm.Similarity_problem"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    type="textarea"
                    placeholder="输入相似的问题，如有多个相似的问题，写法如：申请云主机怎么做/申请云主机"
                  />
              </el-form-item>
              <el-form-item label="答案" prop="answer">
                  <el-input
                    v-model="addForm.answer"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    type="textarea"
                    placeholder="请输入问题的答案"
                  />
              </el-form-item>
            </el-form>
            <!-- 底部区 -->
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="addDialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="add()">确 定</el-button>
                </span>
              </template>
          </el-dialog>
          <el-dialog
            title="预览/下载"
            v-model="isViewPdf20"
            width="50%"
            :close-on-click-modal="false"
            @before-close="closeDialog"
          >
            <div style="width: 100%; height: 500px;">
              <iframe id="pdf-iframe" style="width: 100%; height: 100%; border: none;"></iframe>
            </div>
            <!-- 可以在对话框中添加按钮用于关闭对话框-->
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="isViewPdf20 = false">取 消</el-button>
<!--                <el-button type="primary" @click="add()">下载</el-button>-->
              </span>
            </template>
          </el-dialog>
          <!-- 修改问题的对话框 -->
          <el-dialog title="修改用户" v-model="editDialogVisible" width="40%" @close="editDialogClosed"
          :close-on-click-modal='false'>
            <!-- 内容主体区 -->
            <el-form :model="editUserForm" :rules="editUserFormRules" ref="editUserFormRef" label-width="90px">
              <el-form-item label="编号" prop="id">
                <el-input v-model="editUserForm.id" disabled></el-input>
              </el-form-item>
              <el-form-item label="类型" prop="type">
                  <el-autocomplete
                    v-model="editUserForm.type"
                    :fetch-suggestions="querySearchAsync"
                    placeholder="请输入内容"
                    @select="handleSelect"
                  ></el-autocomplete>
              </el-form-item>
              <el-form-item label="问题" prop="problem">
                <el-input v-model="editUserForm.problem"
                          :autosize="{ minRows: 2, maxRows: 4 }"
                          type="textarea"
                        />
              </el-form-item>
              <el-form-item label="相似问题" prop="Similarity_problem">
                <el-input v-model="editUserForm.Similarity_problem"
                          :autosize="{ minRows: 2, maxRows: 4 }"
                          type="textarea"
                        />
              </el-form-item>
              <el-form-item label="答案" prop="answer">
                <el-input v-model="editUserForm.answer"
                          :autosize="{ minRows: 2, maxRows: 4 }"
                          type="textarea"
                        />
              </el-form-item>
            </el-form>
            <!-- 底部区 -->
              <template #footer>
                <span class="dialog-footer">
                  <el-button @click="editDialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="editUser()">确 定</el-button>
                </span>
              </template>
          </el-dialog>
        </el-card>
    </div>
</template>
<script>
import { defineComponent } from 'vue'
import { Delete, Edit } from '@element-plus/icons-vue'
import {
  ElTable,
  ElTableColumn,
  ElButton,
  ElInput,
  ElDialog,
  ElForm,
  ElFormItem,
  ElMessage,
  ElMessageBox
} from 'element-plus'
export default defineComponent({
  data() {
    return {
      editUserForm: {},
      editDialogVisible: false, //控制修改问题对话框的显示与隐藏
      restaurants: [],
      timeout:  null,
      loading:false,
      users: [],
      //所有角色的数据列表
      roleList: ['CDN','数据库'],
      //获取用户列表的参数对象
      queryInfo: {
        query: "",
        pagenum: 1, //当前的页数
        pagesize: 13, //每页的数量
      },
      total: 0,
      addDialogVisible: false, //控制添加用户对话框的显示与隐藏
      isViewPdf20: false,
      //添加用户的表单数据
      addForm: {},
      //修改表单的验证规则对象
      editUserFormRules: {
        type: [{required: true, message: '请输入问题类型', trigger: 'blur'}],
        problem: [{required: true, message: '请输入问题', trigger: 'blur'}],
        answer: [{required: true, message: '请输入答案', trigger: 'blur'}],
      },
      //添加表单的验证规则对象
      addFormRules: {
        type: [{required: true, message: '请输入问题类型', trigger: 'blur'}],
        problem: [{required: true, message: '请输入问题', trigger: 'blur'}],
        answer: [{required: true, message: '请输入答案', trigger: 'blur'}],
      }
    };
  },
  components: {
    ElTable,
    ElTableColumn,
    ElButton,
    ElInput,
    ElDialog,
    ElForm,
    ElFormItem,
    Edit,
    Delete,
  },
  methods: {
    // 获取所有数据
    async handleEnterKey() {
    // 当按下回车键时，触发搜索按钮的点击事件
      this.getUsers();
    },
    async getUsers() {
      this.loading = true
      try {
        const response = await this.$http.get('/opstion/', {
          params:this.queryInfo
      });
        this.loading = false
        if (response.status === 200) {
          this.users = response.data.results;
          this.total = response.data.total;
        }
        if (response.status === 201) {
          this.users = response.data.results;
          this.total = response.data.total;
          ElMessage.success(response.data.message);
        }
      } catch (error) {
        console.log(error);
        this.getUsers()
        // ElMessage.error('更新用户列表失败！');
      }
    },
    async getselect() {
      try {
        const response = await this.$http.get('/type_select/');
        this.loading = false
        if (response.status === 200) {
          this.restaurants = response.data
        }
      } catch (error) {
        console.log(error);
        this.getUsers()
        // ElMessage.error('更新用户列表失败！');
      }
    },
    //监听 pagesize 改变的事件
    handleSizeChange(newSize){
      // console.log(newSize);
      this.queryInfo.pagesize = newSize;//重新指定每页数据量
      this.queryInfo.pagenum = 1;
      this.getUsers();//带着新的分页请求获取数据
    },
    //监听 页码值 改变的事件
    handleCurrentChange(newPage){
      // console.log(newPage);
      this.queryInfo.pagenum = newPage;//重新指定当前页
      this.getUsers();//带着新的分页请求获取数据
    },
    //监听添加用户对话框的关闭状态
    addDialogClosed(){
      this.$refs.addFormRef.resetFields();
    },
    //关闭编辑用户的对话框
    editDialogClosed(){
      this.$refs.editUserFormRef.resetFields();
    },
    // 点击按钮，添加新用户
    async add(){
      await this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;//校验没通过，返回
        try {
          const response = await this.$http.post("/opstion/", this.addForm);
          console.log(response);
          this.addDialogVisible = false;
          ElMessage.success(response.data.message);
          this.getUsers();
          this.getselect();
        } catch (error) {
          console.log(error);
          ElMessage.error('添加失败！');
        }
      })
    },
    async openDialog() {
      this.isViewPdf20 = true
      // 设置 iframe 的 src 属性以加载网页内容
      const iframe = document.getElementById("pdf-iframe");
      iframe.src = "http://127.0.0.1:8000/pdf/?random=" + Math.random(); // 设置要加载的网页地址
    },
    async closeDialog(done) {
      // 清除 iframe 的 src 属性以关闭网页
      const iframe = document.getElementById("pdf-iframe");
      iframe.src = "about:blank";
      done();
  },

    querySearchAsync(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 30);
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      console.log(item);
    },
    //展示编辑用户的对话框
    async showEditDialog(id) {
      try {
        const response = await this.$http.get('/Data_manipulation/', {
          params: {'id': id}
        });
        this.editUserForm = response.data;
        this.editDialogVisible = true;
        // ElMessage.success('打开成功！');
      } catch (error) {
        console.error(error);
        ElMessage.error('打开失败！');
      }
    },
    async editUser() {
      try {
        const response = await this.$http.post('/Data_manipulation/', {
          id: this.editUserForm.id,
          type: this.editUserForm.type,
          problem: this.editUserForm.problem,
          Similarity_problem: this.editUserForm.Similarity_problem,
          answer: this.editUserForm.answer,
        });
        console.log(response);
        // ElMessage.success('修改用户成功！');
        // 隐藏修改用户的对话框
        this.editDialogVisible = false;
        //重新获取用户列表数据
        this.getUsers();
      } catch (error) {
        console.error(error);
        ElMessage.error('修改用户失败！');
      }
    },
    //根据ID删除对应用户信息
    async removeUserById(id){
      //弹框询问用户是否删除数据
      ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
        try {
          const response = await this.$http.delete('/Data_manipulation/', {
          params: {'id': id}
        });
          console.log(response);
          this.getUsers();
          ElMessage({type: 'success', message: '删除成功!'});
        } catch (error) {
          console.error(error)
          ElMessage.error({message: '删除失败！'});
        }
      }).catch(() => {
        ElMessage.info('已取消删除');
      })
    },
  },
  mounted() {
      this.getUsers()
      this.getselect()
      const button = document.getElementById("yulan");
      button.addEventListener("click", this.openDialog);
    }
})
</script>

<style scoped>
.single-line {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
